package com.blockmeta.bbs.immodule.utils;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.text.Html;
import com.blankj.utilcode.util.LogUtils;
import android.widget.RemoteViews;

import com.blockmeta.bbs.businesslibrary.activity.DeepLinkActivity;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.dao.Todo;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class NotificationHelper {

    private Context mContext;
    private static NotificationHelper mNotificationHelper;
    private NotificationManager mNotificationManager;
    public static final String CHANNEL_ID = "my_channel_02";// The user-visible name of the channel.
    public static final CharSequence CHANNEL_NAME = "8btc";

    /**
     * 用于不同的用户统计显示相应的通知数
     */
    private Map<Long, Integer> mIMNotificationIds;

    private NotificationHelper(Context context) {
        mContext = context;
        mNotificationManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mIMNotificationIds = new ConcurrentHashMap<Long, Integer>();
    }

    public static NotificationHelper getInstance(Context context) {

        if (mNotificationHelper == null) {
            mNotificationHelper = new NotificationHelper(context);
        }
        return mNotificationHelper;

    }

    public void clearNotifyIds(){
        mIMNotificationIds.clear();
    }

    /**
     * 发送通知
     */
    public void sendNotification(String title, String content, String deepLink, long userId, int type) {
        LogUtils.i("notification", android.os.Build.MANUFACTURER + "   ");
//        showCommonNotification(title, content, deepLink, userId);
        //网上抄的，但是发现弹出横幅不需要以下代码，
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            showCommonNotification(title, content, deepLink, userId);
        } else {
            //小米5的手机应用在前台会自动打开APP，后台会正常弹出横幅
            if (android.os.Build.MANUFACTURER.equals("Xiaomi") || android.os.Build.MANUFACTURER.equals("HUAWEI") || android.os.Build.MANUFACTURER.equals("Meizu")) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    //判断是否开启了悬浮通知栏权限   注：部分华为无效
                    if (!Settings.canDrawOverlays(mContext)) {
                        showHangup(title, content, deepLink, userId);
                        return;
                    }
                }
            }
             else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    //判断是否开启了悬浮通知栏权限   注：部分华为无效
                    if (!Settings.canDrawOverlays(mContext)) {
                        showHangup(title, content, deepLink, userId);
                        return;
                    }
                }
            }
        }
        showCommonNotification(title, content, deepLink, userId);

    }

    /**
     * 显示横幅通知
     *
     * @param
     */
    private void showHangup(String title, String content, String deepLink, long userId) {


        long notifyId = getNotifyId(userId);
        if(mIMNotificationIds.keySet().contains(notifyId)){
            mIMNotificationIds.put(notifyId, mIMNotificationIds.get(notifyId) + 1);
        }else {
            mIMNotificationIds.put(notifyId, 1);
        }
        int number = mIMNotificationIds.get(userId);
//        String channelName = channelId
        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, CHANNEL_ID);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
            mNotificationManager.createNotificationChannel(mChannel);
        }
        builder.setSmallIcon(R.drawable.qr_logo);

        builder.setContentTitle(title);
        builder.setContentText(Html.fromHtml(content));
        builder.setNumber(number);

        builder.setAutoCancel(true).setDefaults(
                NotificationCompat.DEFAULT_VIBRATE
                        | NotificationCompat.DEFAULT_SOUND
        );


        Intent intent = new Intent(mContext, DeepLinkActivity.class);
        intent.setData(Uri.parse(deepLink));
        LogUtils.i("notification", "sendcommonNotification" + title + " " + content + " " + deepLink);
        intent.setFlags(
                Intent.FLAG_ACTIVITY_SINGLE_TOP
                        | Intent.FLAG_ACTIVITY_CLEAR_TOP
        );
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, (int) notifyId, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        builder.setContentIntent(pendingIntent);
        builder.setFullScreenIntent(null, true);
        Notification n = builder.build();
        NotificationManagerCompat managerCompat =
                NotificationManagerCompat.from(mContext);

        managerCompat.notify((int) notifyId, n);
    }

    /**
     * 显示普通通知
     */
    private void showCommonNotification(String title, String content, String deepLink, long userId) {
        long notifyId = getNotifyId(userId);
        if(mIMNotificationIds.keySet().contains(notifyId)){
            mIMNotificationIds.put(notifyId, mIMNotificationIds.get(notifyId) + 1);
        }else {
            mIMNotificationIds.put(notifyId, 1);
        }
        int number = mIMNotificationIds.get(userId);
//        String channelName = channelId
        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, CHANNEL_ID);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
            mNotificationManager.createNotificationChannel(mChannel);
        }
        builder.setSmallIcon(R.drawable.qr_logo);

        builder.setContentTitle(title);
        builder.setContentText(Html.fromHtml(content));
        builder.setNumber(number);

        builder.setAutoCancel(true).setDefaults(
                NotificationCompat.DEFAULT_VIBRATE
                        | NotificationCompat.DEFAULT_SOUND
        );


        Intent intent = new Intent(mContext, DeepLinkActivity.class);
        intent.setData(Uri.parse(deepLink));
        LogUtils.i("notification", "sendcommonNotification" + title + " " + content + " " + deepLink);
        intent.setFlags(
                Intent.FLAG_ACTIVITY_SINGLE_TOP
                        | Intent.FLAG_ACTIVITY_CLEAR_TOP
        );
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        builder.setContentIntent(pendingIntent);
        Notification n = builder.build();
        NotificationManagerCompat managerCompat =
                NotificationManagerCompat.from(mContext);

        managerCompat.notify((int) notifyId, n);

    }

    private long getNotifyId(long userId) {
        return userId;
    }

    /**
     * //TODO通知的逻辑
     * //TODO 通知消息的处理
     * 显示代办通知，好友申请，加群申请
     */
    public void showTodoNotify(Todo todo, int userId, String token) {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext, CHANNEL_ID);
        ;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
            mNotificationManager.createNotificationChannel(mChannel);
        }
        RemoteViews mRemoteViews = new RemoteViews(mContext.getPackageName(),
                R.layout.todo_notification_item);
        mRemoteViews.setImageViewResource(R.id.user_photo,
                R.drawable.qr_logo);
        // API3.0 以上的时候显示按钮，否则消失

        mRemoteViews.setTextViewText(R.id.subject, todo.getTodoSubject());
        mRemoteViews.setTextViewText(R.id.request_msg, todo.getRequestMsg());

        // 点击的事件处理
//		Intent buttonIntent = new Intent(Constants.INTENT_ACTION_HANDING_TODO);
//		buttonIntent.putExtra(Constants.INTENT_EXTRA_HANDING_TODO_ID,
//				todo.getTodoId());
        Intent buttonIntent = new Intent(mContext, DeepLinkActivity.class);
        String uriStr = "blockmeta://im/" + (todo.getType() == 1 ? "friend" : "chatgroup_detail?id=" + todo.getGroupId());
        buttonIntent.setData(Uri.parse(uriStr));
        LogUtils.i("notification", "sendNotification" + todo.getTodoSubject() + " " + todo.getRequestMsg() + " " + uriStr);

        PendingIntent intent_paly = PendingIntent.getBroadcast(mContext, 2,
                buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.notification, intent_paly);

        mBuilder.setContent(mRemoteViews)
                .setContentIntent(
                        getDefalutIntent(Notification.FLAG_ONGOING_EVENT))
                .setWhen(System.currentTimeMillis())
                .setCustomBigContentView(mRemoteViews)
                // 通知产生的时间，会在通知信息里显示
                .setTicker(todo.getType() == 1 ? "好友请求" : "加圈请求")// 设置该通知优先级
                .setOngoing(false).setSmallIcon(R.drawable.pic_1);

        Notification notify = mBuilder.build();
//		notify.bigContentView = mRemoteViews;
        notify.flags = Notification.FLAG_AUTO_CANCEL;
        // 会报错，还在找解决思路
        // notify.contentView = mRemoteViews;
        // notify.contentIntent = PendingIntent.getActivity(this, 0, new
        // Intent(), 0);
        mNotificationManager.notify((int) todo.getTodoId(), notify);

    }

    public PendingIntent getDefalutIntent(int flags) {
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 1,
                new Intent(), flags);
        return pendingIntent;
    }
}
